let _this

class Tab {
	constructor(el) {
		_this = this
		this.el = document.querySelector(el)
		this.ul = this.el.querySelector('ul')
    this.addBtn = this.el.querySelector('.add')
    this.contentWarp = this.el.querySelector('.body')
		this.init()
	}
	// 初始化函数

	init() {

    this.lis = this.el.querySelectorAll('li')
    this.contents = this.el.querySelectorAll('.content-item')
    this.close = this.el.querySelectorAll('.close')
		// 将选项卡赋予点击事件
		this.lis.forEach((v, i) => {
			v.index = i
      v.onclick = this.toggleTab
      this.close[i].onclick= this.removeTab
		})
	
		this.addBtn.onclick = this.addTab
	}

	// 切换函数
	toggleTab() {
		// console.log(this.index);
    // console.log(this.index);
    _this.clearClass()
    console.log(this);

		this.className = 'select'
		_this.contents[this.index].className = 'content-item show'
	}
	// 清除class函数
	clearClass() {
		this.lis.forEach((v, i) => {
			v.className = ''
			this.contents[i].className = 'content-item'
		})
	}
	// 增加选项卡
	addTab() {
    let newLi = `<li class = "select" >选项卡${_this.lis.length + 1}
    <span class="close">x</span>
    </li>`
		let newContent = `<div class="content-item show">
                         新内容${_this.lis.length + 1}
                      </div>`

    _this.clearClass()
    _this.ul.insertAdjacentHTML('beforeend', newLi)
    // console.log(_this.contents);
    _this.contentWarp.insertAdjacentHTML('beforeend', newContent)
    _this.init()
  }
  removeTab(e){
    // console.log(this,this.parentNode);
    e.stopPropagation();
    
    let index = this.parentNode.index
    console.log(index);
    // 删除对应的元素节点
    _this.lis[index].remove()
    _this.contents[index].remove()
    _this.init()
    if (document.querySelector('.select')) {
      return
    }
    // index --
    // console.log(_this.lis[index-1]);
    _this.lis[_this.lis.length - 1].click()

  }
}

const tab = new Tab('#app')

console.log(typeof(tab.removeTab));
